using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Extensions.Configuration;

namespace HengTong.Kingdee
{
    /// <summary>
    /// Kingdee EAS WCF 客户端辅助工具
    /// 用于所有 EAS WSDL 服务的统一配置管理
    /// </summary>
    public static class KingdeeEASClientHelper
    {
        private static IConfiguration _configuration;
        private static string _baseUrl;

        /// <summary>
        /// 设置配置对象（在 Startup.cs 中调用一次）
        /// </summary>
        public static void SetConfiguration(IConfiguration configuration)
        {
            _configuration = configuration;
            _baseUrl = configuration["KingdeeEAS:BaseUrl"];
            
            if (string.IsNullOrEmpty(_baseUrl))
            {
                throw new InvalidOperationException("KingdeeEAS:BaseUrl 配置缺失，请在 appsettings.json 中配置");
            }
        }

        /// <summary>
        /// 获取 EAS 服务的完整 URL
        /// </summary>
        /// <param name="servicePath">服务路径，例如：/ormrpc/services/WSExportMaterialGroupFacade</param>
        /// <param name="configuration">可选的配置对象，如果为空则使用全局配置</param>
        /// <returns>完整的服务 URL</returns>
        public static string GetServiceUrl(string servicePath, IConfiguration configuration = null)
        {
            var config = configuration ?? _configuration;
            if (config == null)
            {
                throw new InvalidOperationException("Configuration is not set. Please call SetConfiguration first.");
            }

            var baseUrl = configuration?["KingdeeEAS:BaseUrl"] ?? _baseUrl;
            if (string.IsNullOrEmpty(baseUrl))
            {
                throw new InvalidOperationException("KingdeeEAS:BaseUrl 配置缺失");
            }

            return baseUrl.TrimEnd('/') + servicePath;
        }

        /// <summary>
        /// 创建标准的 BasicHttpBinding
        /// </summary>
        public static BasicHttpBinding CreateStandardBinding()
        {
            return new BasicHttpBinding
            {
                MaxBufferSize = int.MaxValue,
                ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max,
                MaxReceivedMessageSize = int.MaxValue,
                AllowCookies = true,
                OpenTimeout = TimeSpan.FromMinutes(1),
                CloseTimeout = TimeSpan.FromMinutes(1),
                SendTimeout = TimeSpan.FromMinutes(10),
                ReceiveTimeout = TimeSpan.FromMinutes(10)
            };
        }

        /// <summary>
        /// 创建 WCF 客户端的端点地址
        /// </summary>
        public static EndpointAddress CreateEndpointAddress(string servicePath, IConfiguration configuration = null)
        {
            var url = GetServiceUrl(servicePath, configuration);
            return new EndpointAddress(url);
        }

        /// <summary>
        /// 配置服务端点的通用方法
        /// </summary>
        public static void ConfigureEndpoint(ServiceEndpoint serviceEndpoint, ClientCredentials clientCredentials)
        {
            if (serviceEndpoint.Binding is BasicHttpBinding binding)
            {
                binding.MaxBufferSize = int.MaxValue;
                binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
                binding.MaxReceivedMessageSize = int.MaxValue;
                binding.AllowCookies = true;
                binding.OpenTimeout = TimeSpan.FromMinutes(1);
                binding.CloseTimeout = TimeSpan.FromMinutes(1);
                binding.SendTimeout = TimeSpan.FromMinutes(10);
                binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            }
        }
    }
}
